using System.Globalization;
using System.Text;
using System.Xml;
using CalcSharp.Core;
using System;
using CalcSharp.Core.Containers;

namespace CalcSharp
{
    sealed class ScriptRunner
    {
        XmlNode functionnode, rootnode, mainnode;
        XmlDocument script;
        StringBuilder formater;
        public ScriptRunner(string file)
        {
            if (!string.IsNullOrEmpty(file))
            {
                string functname;
                functionnode = null;
                mainnode = null;
                script = new XmlDocument();
                script.Load(MiscFuncts.MakeStream(file));
                foreach (XmlNode node in script.ChildNodes)
                {
                    if (node.Name == "program")
                    {
                        rootnode = node;
                        break;
                    }
                }
                if (rootnode == null) throw new CSException("No program element found, not a valid script!");
                foreach (XmlNode node in rootnode.ChildNodes)
                {
                    if (node.Name == "functions") functionnode = node;
                    else if (node.Name == "main") mainnode = node;
                }
                if (mainnode == null) throw new CSException("No main function found, not a valid script!");
                foreach (XmlNode node in functionnode.ChildNodes)
                {
                    if (node.Name == "function")
                    {
                        if (!string.IsNullOrEmpty(node.Attributes["name"].InnerText))
                        {
                            functname = node.Attributes["name"].InnerText.ToUpper(CultureInfo.CurrentCulture);
                            formater = new StringBuilder(node.InnerText);
                            formater = formater.Replace("\t", "");
                            formater = formater.Replace("\r", "");
                            int req = Convert.ToInt32(node.Attributes["paramsreq"].InnerText);
                            Program.functionmem[functname].code = formater.ToString();
                            Program.functionmem[functname].reqparams = req;
                        }
                        else throw new CSException("One or more functions have no name!");
                    }
                }
            }
        }
        public void Run()
        {
            formater = new StringBuilder(mainnode.InnerText);
            formater = formater.Replace("\t", "");
            formater = formater.Replace("\r", "");
            MiscFuncts.RunBlock(formater.ToString());
        }
    }
}